package sing.core.dialog

import android.app.Activity
import android.content.Intent
import android.net.Uri
import android.os.Build
import android.provider.Settings
import android.view.LayoutInflater
import android.widget.TextView
import androidx.appcompat.app.AlertDialog
import androidx.core.content.FileProvider
import sing.core.BuildConfig
import sing.core.R
import sing.core.callback.Callback
import sing.core.dialog.CustomDialog.OnClickListener
import sing.core.ext.util.loge
import sing.core.ext.util.showShort
import sing.core.util.DownLoadUtil
import sing.core.weight.DownLoadProgressbar
import java.io.File
import java.text.DecimalFormat

class DownloadApk(val activity: Activity,val url:String) {

    private var tvProgress : TextView
    private var progress : DownLoadProgressbar
    private var dialog : CustomDialog
    init {
        val view = LayoutInflater.from(activity).inflate(R.layout.layout_download_apk,null)
        tvProgress = view.findViewById(R.id.tv_progress)
        progress = view.findViewById(R.id.progress)
        dialog = CustomDialog(activity)
        dialog.setTitle("正在下载...")
        dialog.setView(view)
        dialog.hintConfirm()
        dialog.hintCancel()
        dialog.setCancelable(false)
        dialog.show()
    }

    // 确保有WRITE_EXTERNAL_STORAGE权限
    fun start(){
        tvProgress.text = "0MB/0MB"
        val util = DownLoadUtil(activity, url)
        util.downLoadFile(object : DownLoadUtil.Callback {
            override fun success(url: String, localPath: String) {
                installApk(File(localPath),activity)
            }

            override fun failure(url: String?, errorMsg: String) {
                progress.setCurrentValue(0F)
                "下载失败:$errorMsg".showShort()
                dialog.dismiss()
            }

            override fun process(current: Long, total: Long) {
                if (current <= total) {
                    tvProgress.text = "${getMB(current)}/${getMB(total)}"
                    progress.setMaxValue(total.toFloat())
                    progress.setCurrentValue(current.toFloat())
                }
                "当前已下载：$current".loge()
            }
        })
    }

    fun installApk(apk:File,activity: Activity){
        if (checkInstallPermission(activity)){
            if (!apk.exists() && apk.isFile){
                "安装包不存在".showShort()
                return
            }
            dialog.dismiss()
            val intent = Intent(Intent.ACTION_VIEW)
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                val contentUri = FileProvider.getUriForFile(activity, BuildConfig.AUTHORITIES, apk)
                intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
                intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
                intent.setDataAndType(contentUri, "application/vnd.android.package-archive")
            } else {
                intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
                intent.setDataAndType(Uri.fromFile(apk), "application/vnd.android.package-archive")
            }
            activity.startActivity(intent)

            val d = CustomDialog(activity)
            d.setCancelable(false)
            d.setMsg("是否已经安装？")
            d.setCancel("取消")
            d.setConfirm("安装")
            d.addListener(object :OnClickListener{
                override fun confirm(dialog: AlertDialog?) {
                    super.confirm(dialog)
                    installApk(apk, activity)
                }
            })
            d.show()
        }else{ // 没有权限
            ToOpenPermission.requestDialog(activity, "安装权限", object : Callback {
                override fun result(vararg data: Any) {
                    if (data[0] == 0){
                        dialog.dismiss()
                    }else if (data[0] == 1){
                        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                            val packageURI = Uri.parse("package:" + activity.packageName)
                            val intent = Intent(Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES, packageURI)
                            activity.startActivity(intent)

                            dialog.dismiss()

                            val d = CustomDialog(activity)
                            d.setCancelable(false)
                            d.setMsg("是否打开权限？")
                            d.setCancel("取消")
                            d.setConfirm("再次尝试")
                            d.addListener(object :OnClickListener{
                                override fun confirm(dialog: AlertDialog?) {
                                    super.confirm(dialog)
                                    installApk(apk, activity)
                                }
                            })
                            d.show()
                        }
                    }
                }
            },false)
        }
    }

    // 请求安装权限
    private fun checkInstallPermission(activity: Activity):Boolean{
        return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            val haveInstallPermission = activity.packageManager.canRequestPackageInstalls()
            haveInstallPermission
        }else{
            true
        }
    }

    private fun getMB(size: Long): String {
        val mb = 1024 * 1024 //定义MB的计算常量
        val df = DecimalFormat("0.00") //格式化小数
        val result = df.format((size / mb.toFloat()).toDouble())
        return result + "MB"
    }
}